package com.example.tranport.client.message;

import com.example.destination.JmsDestination;
import com.example.destination.JmsListener;
import com.example.message.JmsMessageWrapper;
import com.example.message.Request;
import com.example.message.RequestType;
import com.example.tranport.client.ClientFactory;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

public class ClientMessageServiceImpl implements ClientMessageService {

    Logger logger = LoggerFactory.getLogger(ClientMessageServiceImpl.class);

    private ClientFactory clientFactory;

    public ClientMessageServiceImpl(ClientFactory clientFactory) {
        this.clientFactory = clientFactory;
    }

    @Override
    public void sessionOpened(IoSession ioSession) throws Exception {
        List<JmsDestination> destinations = clientFactory.getClientDestinationService().getDestinations();
        if (!destinations.isEmpty()) {
            Request request = new Request();
            request.setType(RequestType.REGISTER);
            request.setData(destinations);
            ioSession.write(request);
            logger.warn("客户端注册消息监听对象: " + destinations);
        }
    }

    @Override
    public void sessionClosed(IoSession ioSession) throws Exception {

    }

    /***
     * 客户端接收到消息处理
     * @param ioSession
     * @param message
     * @throws Exception
     */
    @Override
    public void messageReceived(IoSession ioSession, Object message) throws Exception {
        if (message instanceof Request) {
            if (((Request) message).getType().equalsIgnoreCase(RequestType.RECEIVE_QUEUE)) {
                JmsMessageWrapper jmsMessageWrapper = (JmsMessageWrapper) ((Request) message).getData();
                List<JmsDestination> jmsDestinations = clientFactory.getClientDestinationService().getDestination(jmsMessageWrapper.getName());
                for (JmsDestination jmsDestination : jmsDestinations) {
                    if (jmsDestination.isAutoCommit()){
                        try {
                            JmsListener jmsListener = (JmsListener) clientFactory.getApplicationContext().getBean(jmsDestination.getBeanName());
                            jmsListener.onMessage(jmsMessageWrapper);
                        } catch (Exception e) {
                            logger.error("客户端消息消息出错: " + e.getMessage());
                        } finally {
                           jmsMessageWrapper.acknowledge();
                        }
                    }
                }
            }
        }
    }
}
